package me.qingy.security;

import com.google.code.kaptcha.Producer;
import me.qingy.common.constant.Constants;
import me.qingy.common.utils.Base64;
import me.qingy.common.utils.IdUtils;
import me.qingy.core.entity.Menu;
import me.qingy.core.service.MenuService;
import me.qingy.common.result.AjaxResult;
import me.qingy.security.model.LoginBody;
import me.qingy.web.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author qingy
 * @since 2021-05-11
 */
@Controller
public class SecurityController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    @ResponseBody
    public String login(@RequestBody LoginBody loginBody) {
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());

        return token;
    }

    @GetMapping("index.html")
    public String index(String token, Model model) {
        List<Menu> menus = menuService.list();
        model.addAttribute("menus", menus);
        model.addAttribute("token", token);
        return "index";
    }

    @PreAuthorize("@ss.hasPermi('system:user:view')")
    @GetMapping("/system/user")
    @ResponseBody
    public String user() {
        return "<h1>允许访问<h1>";
    }

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    private final String captchaType = "math";

    @GetMapping(value = "/captchaImage")
    @ResponseBody
    public AjaxResult getCode() {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisTemplate.opsForValue().set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

}
